import cPickle as pickle
import getopt
import sys
import httplib
import getpass
import base64
import urllib
import os.path
import datetime
from caldavclientlibrary.protocol.webdav.definitions import davxml
from caldavclientlibrary.protocol.url import URL
from caldavclientlibrary.protocol.webdav.propfind import PropFind
from caldavclientlibrary.protocol.webdav.propall import PropAll
from caldavclientlibrary.client.clientsession import CalDAVSession

PFILE = "events.pickle"

#Utility fxn
def date_today():
	today = datetime.date.today()
	month = today.month
	if month < 10:
		month = "0" + str(month)
	day = today.day
	if day < 10:
		day = "0" + str(day)
	return str(today.year) + month + day

#Class to use a subset of open source caldav library
class CaldavConnection(CalDAVSession):

	def __init__(self, username, password, url, log):
		self.urlObj = URL(url)
		self.dateEventPairs = []
		#Setting the port parameter does not satisfy how later code looks for port info
		super(CaldavConnection, self).__init__(self.urlObj.server, root=self.urlObj.relativeURL(), ssl=True, user=username, pswd=password, logging=log)

	class Reservation:

		def __init__(self):
			self.name = ""
			self.project = ""
			self.host = []
			self.network = ""
			self.startTime = ""


	def get_events_today(self):
		try:
			f = open(PFILE)
			self.dateEventPairs = pickle.load(f)
			f.close()
		except IOError as err:
			print err
		if not self.dateEventPairs:
			results = self.getPropertiesOnHierarchy(self.urlObj, (davxml.resourcetype,))
			#results is a dict of href strings and PropFindResult objs
			eventIds = results.keys()
			#Find events for today
			for evId in eventIds:
				if not evId == self.urlObj.relativeURL():
					eData, etag = self.readData(URL(os.path.join(self.urlObj.absoluteURL(), evId)))
					startInfo = None
					endInfo = None
					for line in eData.splitlines():
						if line.startswith("DTSTART;TZID") or line.startswith("DTSTART;VALUE="):
							startInfo = line
						if line.startswith("DTEND;TZID") or line.startswith("DTEND;VALUE="):
							endInfo = line
						if startInfo and endInfo:
							self.dateEventPairs.append( (startInfo, endInfo, eData, evId))
							break
			f = open(PFILE,'w')
			pickle.dump(self.dateEventPairs, f)
			f.close()

		#check what we have
		#for (sd,ed, ev, eId) in self.dateEventPairs:
		#	print sd
		#	print ed
		#	print "----------"

		#eventsToday = [ (dt,ev,eId) for (dt, ev, eId) in self.dateEventPairs if dt.rsplit(':',1)[1].startswith(date_today())]
		eventsToday = []
		for (sd, ed, ev, eId) in self.dateEventPairs:
			beginDate = sd.rsplit(':',1)[1].split('T',1)[0]
			today = date_today()
			if beginDate == today:
				eventsToday.append( (sd, ed,ev,eId))
			elif (int(beginDate) < int(today)) and (int(ed.rsplit(':',1)[1].split('T',1)[0]) >= int(today)):
				eventsToday.append( (sd, ed,ev,eId))

		#NOTE: Events spanning multiple days do not have
		#      true end date time values - must be calculated
		#      from the recurrence values.

		print "Today's Events: "
		for (sd,ed,ev,eId) in eventsToday:
			print "-----------------------"
			print "id: " + eId
			print ev
			print "-----------------------"

		reservations = []
		for (sd,ed, ev, eId) in eventsToday:
			res = CaldavConnection.Reservation()
			res.startTime = sd
			for line in ev.splitlines():
				if line.startswith("SUMMARY"):
					summary = line.rsplit(':',1)[1]
					#Fill in reservation
					print "Summary: " + summary

					break
			

def run(username, password, url, logging):
	#Create headers
	caldav = CaldavConnection(username, password, url, logging)
	caldav.get_events_today()


if __name__ == "__main__":
	options, args = getopt.getopt(sys.argv[1:], "l", ["user=","passwd=","url="])
	options = dict(options)
	if not "--url" in options:
		options["--url"] = raw_input("Enter url (include http:..) ")
	if not "--user" in options:
		options["--user"] = raw_input("Enter user name: ")
	if not "--passwd" in options:
		options["--passwd"] = getpass.getpass()
	logging = False
	if "-l" in options:
		logging = True
	#the url for events needs to end in '/'
	if not options["--url"].endswith("/"):
		options["--url"] += "/"
	run(options["--user"], options["--passwd"], options["--url"], logging)
